package com.fenqing.leetcode.code.t500_600;

import com.fenqing.annotations.Execute;
import com.fenqing.core.Topic;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

public class Topic542 extends Topic {
    /**
     * 构造器
     *
     * @param input 输入
     */
    public Topic542(String input) {
        super(input);
    }

    @Execute
    public int[][] updateMatrix(int[][] mat) {
        int xLen = mat.length, yLen = mat[0].length;
        int[][] newArray = new int[xLen][yLen];
        Queue<int[]> zero = new ArrayDeque<>();
        boolean[][] use = new boolean[xLen][yLen];
        for (int i = 0; i < xLen; i++) {
            for (int j = 0; j < yLen; j++) {
                if (mat[i][j] == 0){
                    zero.offer(new int[]{i, j});
                    use[i][j] = true;
                }
            }
        }
        int num = 0;

        while (!zero.isEmpty()){
            int size = zero.size();
            for (int i = 0; i < size; i++) {
                int[] poll = zero.poll();
                if (poll != null) {
                    int x = poll[0], y = poll[1];
                    newArray[x][y] = num;
                    int x1 = x - 1, x2 = x + 1, y1 = y - 1, y2 = y + 1;
                    if (x1 >= 0 && !use[x1][y]) {
                        zero.offer(new int[]{x1, y});
                        use[x1][y] = true;
                    }
                    if (x2 < xLen && !use[x2][y]) {
                        zero.offer(new int[]{x2, y});
                        use[x2][y] = true;
                    }
                    if (y1 >= 0 && !use[x][y1]) {
                        zero.offer(new int[]{x, y1});
                        use[x][y1] = true;
                    }
                    if (y2 < yLen && !use[x][y2]) {
                        zero.offer(new int[]{x, y2});
                        use[x][y2] = true;
                    }
                }
            }
            num++;
        }
        return newArray;
    }

    public static void main(String[] args) {
        Topic542 topic542 = new Topic542("[[0,0,0],[0,1,0],[1,1,1]]");
        System.out.println(Arrays.deepToString(topic542.run()));
    }
}
